package com.ruoyi.web.controller.shop.service.Impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.ShopConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.entity.DO.shop.ShopAppletDO;
import com.ruoyi.common.entity.DO.shop.ShopDO;
import com.ruoyi.common.entity.VO.shop.ShopAppletVO;
import com.ruoyi.common.entity.VO.shop.ShopChangeParentVO;
import com.ruoyi.common.entity.VO.shop.ShopSearchVO;
import com.ruoyi.common.entity.VO.shop.ShopVO;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.product.service.IBackProductService;
import com.ruoyi.web.controller.shop.mapper.IBackShopMapper;
import com.ruoyi.web.controller.shop.service.IBackShopAppletService;
import com.ruoyi.web.controller.shop.service.IBackShopConfigService;
import com.ruoyi.web.controller.shop.service.IBackShopService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BackShopServiceImpl implements IBackShopService {
    @Resource
    private IBackShopMapper shopMapper;

    @Resource
    private IBackShopConfigService shopConfigService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private IBackShopAppletService shopAppletService;

    @Resource
    private IBackProductService productService;

    @Override
    public List<ShopVO> searchList(ShopSearchVO shopSearchVO) {
        shopSearchVO.setIsDelete(0);
        return shopMapper.searchList(shopSearchVO);
    }

    @Override
    public List<Long> searchChildIdList(Long parentId) {
        return shopMapper.searchChildIdList(parentId);
    }

    @Override
    public ShopVO getShopInfoById(Long shopId) {
        return shopMapper.getShopInfoById(shopId);
    }

    @Override
    public int insertShop(ShopVO shopVO) {
        ShopDO shopDO = new ShopDO();
        shopDO.setShopName(shopVO.getShopName());
        shopDO.setShopAddress(shopVO.getShopAddress());
        shopDO.setApplicantName(shopVO.getApplicantName());
        shopDO.setApplicantPhone(shopVO.getApplicantPhone());
        shopDO.setBusinessLicenceNum(shopVO.getBusinessLicenceNum());
        shopDO.setBusinessLicenceImg(shopVO.getBusinessLicenceImg());
        shopDO.setCreateTime(new Date());
        shopDO.setCreateBy(shopVO.getCreateBy());
        shopDO.setIsDelete(0);
        return shopMapper.insertSelective(shopDO);
    }

    @Override
    @Transactional
    public int updateShop(ShopVO shopVO) {
        ShopDO shopDO = shopMapper.selectByPrimaryKey(shopVO.getId());
        if (shopDO == null || shopDO.getIsDelete() == 1) {
            throw new BusinessException("店铺已被删除，请刷新后重试！");
        }
        if (shopVO.getReviewStatus() != null
                && !shopDO.getReviewStatus().equals(shopVO.getReviewStatus())
                && shopVO.getReviewStatus() == ShopConstants.ReviewStatusEnum.AGREE.getValue()) {
            //TODO:店铺审核通过
            if (shopDO.getUid() == null || shopDO.getUid() == 0) {
                //TODO:创建账号
                //TODO:生成一个后台账号（拥有店铺权限）
                SysUser user = new SysUser();
                user.setShopId(106L);
                //名称为店铺名称
                user.setUserName(shopVO.getShopName());
                //登录账号为申请人手机号
                user.setLoginName(shopVO.getApplicantPhone());
                user.setPhonenumber(shopVO.getApplicantPhone());
                //密码为申请人手机号后6位
                user.setSalt(ShiroUtils.randomSalt());
                user.setPassword(new Md5Hash(user.getLoginName() + shopVO.getApplicantPhone().substring(5) + user.getSalt()).toHex());
                user.setEmail(shopVO.getApplicantPhone() + "@163.com");
                user.setAvatar(shopVO.getShopLogo());
                user.setStatus("0");
                user.setSex("1");
                user.setCreateBy("店铺审核通过自动生成");
                user.setRoleIds(new Long[]{2L});
                user.setPostIds(new Long[]{1L});
                sysUserService.insertUser(user);
                shopDO.setUid(user.getUserId());
            }
            ShopAppletDO shopApplet = shopAppletService.getShopAppletInfoByShopId(shopDO.getId());
            if (shopApplet == null) {
                //TODO:新增小程序
                ShopAppletVO shopAppletVO = new ShopAppletVO();
                shopAppletVO.setShopId(shopDO.getId());
                shopAppletVO.setCreateBy("店铺审核通过自动生成");
                shopAppletVO.setCreateTime(new Date());
                shopAppletService.insertShopApplet(shopAppletVO);
            }
            //TODO:更新全局配置
            shopConfigService.refresh(shopDO.getId(), true);
            //TODO:同步商品
//            productService.syncProductToShop(shopDO.getId());
        }
        shopDO.setShopName(shopVO.getShopName());
        shopDO.setShopTel(shopVO.getShopTel());
        shopDO.setShopAddress(shopVO.getShopAddress());
        shopDO.setShopLogo(shopVO.getShopLogo());
        shopDO.setShopCode(shopVO.getShopCode());
        shopDO.setReviewStatus(shopVO.getReviewStatus());
        shopDO.setApplicantName(shopVO.getApplicantName());
        shopDO.setApplicantPhone(shopVO.getApplicantPhone());
        shopDO.setApplicantEmail(shopVO.getApplicantEmail());
        shopDO.setBusinessLicenceNum(shopVO.getBusinessLicenceNum());
        shopDO.setBusinessLicenceImg(shopVO.getBusinessLicenceImg());
        shopDO.setIsEnable(shopVO.getIsEnable());
        shopDO.setUpdateTime(new Date());
        shopDO.setUpdateBy(shopVO.getUpdateBy());
        return shopMapper.updateByPrimaryKeySelective(shopDO);
    }

    @Override
    public String checkShopNameUnique(ShopSearchVO shopSearchVO) {
        Long shopId = StringUtils.isNull(shopSearchVO.getShopId()) ? -1L : shopSearchVO.getShopId();
        Long existId = shopMapper.getIdByShopName(shopSearchVO.getShopName());
        if (existId != null && !shopId.equals(existId)) {
            return Constants.FAIL;
        }
        return Constants.SUCCESS;
    }

    @Override
    public String checkShopCodeUnique(ShopSearchVO shopSearchVO) {
        Long shopId = StringUtils.isNull(shopSearchVO.getShopId()) ? -1L : shopSearchVO.getShopId();
        Long existId = shopMapper.getIdByShopCode(shopSearchVO.getShopCode());
        if (existId != null && !shopId.equals(existId)) {
            return Constants.FAIL;
        }
        return Constants.SUCCESS;
    }

    @Override
    public int deleteShopById(Long id) {
        return shopMapper.deleteShopById(id);
    }

    @Override
    public ShopVO getShopInfoByAppId(String appId) {
        return shopMapper.getShopInfoByAppId(appId);
    }

    /**
     * 查询店铺树
     *
     * @param shopSearchVO 店铺查询信息
     * @return 所有店铺信息
     */
    @Override
    public List<Ztree> selectShopTree(ShopSearchVO shopSearchVO) {
        shopSearchVO.setIsDelete(0);
        shopSearchVO.setReviewStatus(1);
        List<ShopVO> shopList = shopMapper.searchList(shopSearchVO);
        List<Ztree> ztrees = initZtree(shopList);
        return ztrees;
    }

    @Override
    public void changeParentHandle(ShopChangeParentVO shopChangeParentVO) {
        ShopDO shopDO = shopMapper.selectByPrimaryKey(shopChangeParentVO.getShopId());
        if (shopDO == null || shopDO.getIsDelete() == 1) {
            throw new BusinessException("店铺已被删除，请刷新后重试！");
        }
        ShopDO shopParentDO = shopMapper.selectByPrimaryKey(shopChangeParentVO.getParentId());
        if (shopParentDO == null || shopParentDO.getIsDelete() == 1) {
            throw new BusinessException("上级店铺已被删除，请刷新后重试！");
        }
        if (shopParentDO.getReviewStatus() == 0) {
            throw new BusinessException("上级店铺未审核通过！");
        }
        if (shopParentDO.getIsEnable() == 0) {
            throw new BusinessException("上级店铺已被下架！");
        }
        shopDO.setParentId(shopChangeParentVO.getParentId());
        shopMapper.updateByPrimaryKeySelective(shopDO);
    }

    /**
     * 对象转店铺树
     *
     * @param shopList 店铺列表
     * @return 树结构列表
     */
    private List<Ztree> initZtree(List<ShopVO> shopList) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (ShopVO shop : shopList) {
            Ztree ztree = new Ztree();
            ztree.setId(shop.getId());
            ztree.setpId(shop.getParentId());
            ztree.setName(shop.getShopName());
            ztree.setTitle(shop.getShopName());
            ztrees.add(ztree);
        }
        return ztrees;
    }
}